package cn.bone.demo.mongo;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;

/**
 * Created by superbone on 2016/9/24.
 */
public class MongoFactory {

    private static Morphia morphia;
    private static Datastore datastore;
    private static MongoClient mongoClient;
    private static MongoDatabase mongoDatabase;
    private static String url = "mongodb://121.40.129.226";
    private static String dbName = "demo";
    static {

        //初始化mongodb相关类
        MongoClientURI clientURI = new MongoClientURI(url);
        mongoClient = new MongoClient(clientURI);
        mongoDatabase = mongoClient.getDatabase(dbName);

        //初始化morphia相关类
        morphia = new Morphia();
        morphia.mapPackage("cn.bone.demo.**");
        datastore = morphia.createDatastore(mongoClient,dbName);
        datastore.ensureIndexes();
    }
    private MongoFactory(){}

    public static Datastore getDatastore(){
        return datastore;
    }

    public static MongoDatabase getMongoDatabase(){
        return mongoDatabase;
    }

    public static void close(){

        if(mongoClient!=null){
            mongoClient.close();
        }
    }

}
